const fs = require('fs');
const glob = require('glob')
const {createpart} = require('./template')
const folderpath = require('./folderpath')

function getNameAndPath({pagename}) {
	//各种名称
	let typesName = 'UPDATEPAGE'
	let storeName = 'page'
	let reducerName = 'page'
	let actionName = 'DOREQUEST'
	let componentName = '';
	let pagenameSplit = pagename.split('-')
	const getrandom = () => {
		let arr = [1, 2, 3, 4, 5]
		let random = ''
		arr.forEach(() => {
			random += Math.floor(Math.random() * 10)
		})
		return '_id' + random
	}
	
	pagenameSplit.forEach((data, index) => {
		// if (index >= 1) {
		// 	let datain = data.replace(data.charAt(0), data.charAt(0).toUpperCase())
		// 	componentName += datain
		// } else {
		// 	componentName += data
		// }
		let datain = data.replace(data.charAt(0), data.charAt(0).toUpperCase())
		componentName += datain
		typesName += data.toUpperCase()
		storeName += data.toLowerCase()
		reducerName += data.toLowerCase()
		actionName += data.toUpperCase()
	})
	let className = componentName + getrandom()
	//pages里面的文件
	let pagespath = `${__dirname}/../${folderpath.pagespath}`
	let subpagespath = `${__dirname}/../${folderpath.subpagespath}`
	
	return {
		filename: {
			typesName,
			storeName,
			reducerName,
			actionName,
			componentName,
			className,
			pagename
		},
		filepath: {
			pagespath,
			subpagespath
		}
	}
}

// 获取指定路径下的入口文件
function getEntries(globPath) {
	let files = glob.sync(globPath) || [];
	let entries = [];
	files.forEach(function (filepath) {
		// 取倒数第二层(view下面的文件夹)做包名
		let name = filepath.split('/');
		let namereplace = name[name.length - 1].replace('.js', '')
		if (namereplace != 'index') {
			entries.push(namereplace)
		}
	});
	return entries;
}

function addPagepathToJumplist({pagepath, pagename, pagechinesename}) {
	const {pageurlpath} = require('./config')
	const path = `${__dirname}/../${pageurlpath}`
	const pagejumplist = require(path);
	pagejumplist[pagename] = {
		"name": pagechinesename,
		"path": pagepath
	}
	fs.writeFile(path, Buffer.from(JSON.stringify(pagejumplist, null, 2)), function (err) {
		if (err) {
			console.log('写入pagejumplist失败！');
		}
	});
}

function updateStoreIndex() {//更新store reducer index。js;
	//reducers/index.js
	let reducersindexTeptop = '';
	let reducersindexTepbtn = '';
	let entriesreducers = getEntries(`${__dirname}/../src/store/reducers/*.js`);
	const pagesnamearray = fs.readdirSync(`${__dirname}/../src/pages`)
	// console.log(pagesnamearray, entriesreducers, 'entriesreducerscommon');
	entriesreducers.forEach((data) => {
		if(!data.match(/\./g)) {
			reducersindexTeptop += `import ${data} from './${data}';\r\n`
			reducersindexTepbtn += `  ${data},\r\n`
		}
	})
	pagesnamearray.forEach((data) => {
		let pagename = data
		let pagenamesplit = data.split('-')
		let reducername = 'page'
		pagenamesplit.forEach((data) => {
			reducername += data
		})
		if(!data.match(/\./g)) {
			reducersindexTeptop += `import ${reducername} from '../../pages/${pagename}/store/reducers/${reducername}';\r\n`
			reducersindexTepbtn += `  ${reducername},\r\n`
		}
	})
	
	let reducersindexTepfinal =
		`${reducersindexTeptop}
export default {
${reducersindexTepbtn}
}`
	fs.writeFileSync(`${__dirname}/../src/store/reducers/index.js`, reducersindexTepfinal);
}

function createpagefile({path, pageTemplate, pagecssTemplate, storeName, actionsTemplate, reducersTemplate, typesTemplate, pagename, pagechinesename, issub}) {
	fs.access(`${path}`, function (err) {
		if (err) {
			let pagepath = ''
			fs.mkdirSync(`${path}`);
			fs.mkdirSync(`${path}/components`);
			fs.mkdirSync(`${path}/store`);
			fs.mkdirSync(`${path}/store/actions`);
			fs.mkdirSync(`${path}/store/reducers`);
			fs.mkdirSync(`${path}/store/types`);
			
			fs.writeFileSync(`${path}/index.js`, pageTemplate);
			fs.writeFileSync(`${path}/index.less`, pagecssTemplate);
			
			let pathactions = `${path}/store/actions/${storeName}.js`
			let pathreduces = `${path}/store/reducers/${storeName}.js`
			let pathtypes = `${path}/store/types/${storeName}.js`
			
			fs.writeFileSync(pathactions, actionsTemplate);
			fs.writeFileSync(pathreduces, reducersTemplate);
			fs.writeFileSync(pathtypes, typesTemplate);
			if (issub == 2) {
				pagepath = `/subpackages/pages/${pagename}/index`
				console.log(`模版创建完成 请将路径弄到src/app.js里面的subPackages里 pages/${pagename}/index ！！！`)
			} else {
				pagepath = `/pages/${pagename}/index`
				console.log(`模版创建完成 请将路径弄到src/app.js里面的pages里 pages/${pagename}/index ！！！`)
				updateStoreIndex()
			}
			addPagepathToJumplist({pagepath, pagename, pagechinesename})
		} else {
			console.log(`${path} 文件夹已存在！！！`)
		}
	})
}

function createcomponentfile({path, compTemplate, compcssTemplate}) {
	fs.access(`${path}`, function (err) {
		if (err) {
			fs.mkdirSync(`${path}`);
			fs.writeFileSync(`${path}/index.js`, compTemplate);
			fs.writeFileSync(`${path}/index.less`, compcssTemplate);
			console.log(`组件模版创建完成 666!`)
		} else {
			console.log(`${path} 文件夹已存在！！！`)
		}
	})
}

module.exports = {
	createpage: function ({pagename, issub, pagechinesename}) {
		const {filename, filepath} = getNameAndPath({pagename})
		const {storeName} = filename
		const {pageTemplate, pagecssTemplate, actionsTemplate, reducersTemplate, typesTemplate} = createpart({
			...filename,
			issub,
			pagechinesename
		})
		let path;
		if (issub == 2) {
			path = `${filepath.subpagespath}/${filename.pagename}`
		} else {
			path = `${filepath.pagespath}/${filename.pagename}`
		}
		createpagefile({
			path,
			pageTemplate,
			pagecssTemplate,
			storeName,
			actionsTemplate,
			reducersTemplate,
			typesTemplate,
			issub,
			pagename,
			pagechinesename
		})
	},
	createcomponent: function ({pathchoose, compoentname}) {
		const {filename} = getNameAndPath({pagename: compoentname})
		let path = `${pathchoose}/${filename.pagename}`
		const {compTemplate, compcssTemplate} = createpart({...filename})
		createcomponentfile({path, compTemplate, compcssTemplate})
	},
	updateStore: function () {
		updateStoreIndex()
	}
}
